package cn.eonshine.cuba.lsms.modular.biz.service.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import cn.eonshine.cuba.inf.common.util.DateUtils;
import cn.eonshine.cuba.inf.common.http.InfStatus;
import cn.eonshine.cuba.inf.modular.biz.entity.TankerGpsInf;
import cn.eonshine.cuba.lsms.modular.CommonService;
import cn.eonshine.cuba.lsms.modular.basic.entity.Tanker;
import cn.eonshine.cuba.lsms.modular.basic.service.ITankerService;
import cn.eonshine.cuba.lsms.modular.biz.entity.ETankerExecutionInformation;
import cn.eonshine.cuba.lsms.modular.biz.service.IETankerExecutionInformationService;
import cn.eonshine.cuba.lsms.modular.biz.service.IETankerExecutionService;
/**
 * 实时船舶信息维护
 * @author Administrator
 *
 */
@Service
public class EtankExecutionService extends CommonService<TankerGpsInf> implements IETankerExecutionInformationService{
	
	@Autowired
	private IETankerExecutionService iETankerExecutionService;
	@Autowired
	private ITankerService iTankerService;

	private final String listUrl = "/tankerGpsInf/list";
	private final String updateUrl = "/tankerGpsInf/update";
	/*
	 * (non-Javadoc)
	 * 
	 * @see cn.eonshine.cuba.inf.modular.lsms.basic.service.IInventoryDataService#
	 * requestInventoryData()
	 */
	public void requestExecution() {
		requestData(listUrl, updateUrl, InfStatus.INF_LOG_TYPE.BARCO_GPS_NUM);
	}
	
	protected Object dataHandle(TankerGpsInf tankerGpsInf) throws Exception {
		if(StringUtils.isBlank(tankerGpsInf.getImoNumber())) {
//			return null;
			throw new Exception("miss imo number: "+tankerGpsInf.toString());
		}
		QueryWrapper<Tanker> QueryWrapper = new QueryWrapper<Tanker>();
		QueryWrapper.eq("TANKER_IMO", tankerGpsInf.getImoNumber());
		Tanker tanker = iTankerService.getOne(QueryWrapper);
		if(tanker == null || StringUtils.isBlank(tanker.getId())) {
			throw new Exception("Tanker imo not match in SISTLOG, tanker imo number: "+tankerGpsInf.getImoNumber()+" . and VESSEL_ID : "+tankerGpsInf.getVesselId().toString());
		}
		QueryWrapper<ETankerExecutionInformation> entity = new QueryWrapper<ETankerExecutionInformation>();
		// check if exsists in database
		//entity.where("is_his='0' and tanker_id={0}", tanker.getId());
		entity.lambda().eq(ETankerExecutionInformation::getIsHis, InfStatus.GPS_IS_HIS_NO);
		entity.lambda().eq(ETankerExecutionInformation::getTankerId, tanker.getId());
		
		ETankerExecutionInformation curentBuque = iETankerExecutionService.getOne(entity);
		if(curentBuque != null) { // exsists set 
			curentBuque.setIsHis(InfStatus.GPS_IS_HIS_YES);
			iETankerExecutionService.update(curentBuque, entity);
		}
		
		entity = new QueryWrapper<ETankerExecutionInformation>();
		Date datatime=timeConversion(tankerGpsInf.getDataTime());
		if(datatime!=null) {
			//entity.where("data_time={0} and tanker_id={1} ", datatime, tanker.getId());
			entity.lambda().eq(ETankerExecutionInformation::getDataTime, datatime);
			entity.lambda().eq(ETankerExecutionInformation::getTankerId, tanker.getId());
		}else {
			throw new Exception("miss datatime: "+tankerGpsInf.toString());
//			return null;
		}
		ETankerExecutionInformation info = iETankerExecutionService.getOne(entity);
		boolean isInsert = false;
		if (info == null) {
			info = new ETankerExecutionInformation();
			isInsert = true;
		}
		info.setTankerId(tanker.getId());
		info.setIsHis(InfStatus.GPS_IS_HIS_NO);
		info.setStarPortId(tankerGpsInf.getStarPortId());
		info.setEndPortId(tankerGpsInf.getEndPortId());
		Date startDate=timeConversion(tankerGpsInf.getStartTime());
		if(startDate!=null) {
			info.setStartTime(startDate);
		}else {
//			return null;
//			throw new Exception("miss start_date: "+tankerGpsInf.toString());
		}
		Date endDate=timeConversion(tankerGpsInf.getEndTime());
		if(endDate!=null) {
			info.setEndTime(endDate);
		}else {
//			return null;
//			throw new Exception("miss end_date: "+tankerGpsInf.toString());
		}
		if(datatime!=null) {
			info.setDataTime(datatime);
		} else {
//			return null;
			throw new Exception("miss dataTime: "+tankerGpsInf.toString());
		}
		info.setLatitude(tankerGpsInf.getLatitude());
		info.setCreateBy(InfStatus.CREATE_BY);
		if(isInsert) {
			info.setCreateDate(tankerGpsInf.getDataInputDatetime());
		}
		info.setUpdateBy(InfStatus.UPDATE_BY);
		if(tankerGpsInf.getDataInputDatetime() !=null) {
			info.setUpdateDate(tankerGpsInf.getDataInputDatetime());
		}else {
			info.setUpdateDate(DateUtils.getCubaDate(Calendar.getInstance().getTime()));
		}
		info.setLongitude(tankerGpsInf.getLongitude());
		info.setAvgSpeed(tankerGpsInf.getAvgSpeed());
		info.setMaxSpeed(tankerGpsInf.getMaxSpeed());
		
		if (isInsert) {
			iETankerExecutionService.save(info);
		} else {
			iETankerExecutionService.updateById(info);
		}
		return info;
	}
	
	@Override
	protected List<TankerGpsInf> feadBackDataHandle(Object obj, TankerGpsInf tankerGpsInf, List<TankerGpsInf> feadBackDataLists) throws Exception {
		ETankerExecutionInformation info = (ETankerExecutionInformation) obj;
		TankerGpsInf tmpBack = new TankerGpsInf();
		tmpBack.setVesselId(tankerGpsInf.getVesselId());
		tmpBack.setDataInputDatetime(tankerGpsInf.getDataInputDatetime());
		tmpBack.setLsmsUpdate(InfStatus.LSMS_UPDATE_EXTRACT_YES);
		feadBackDataLists.add(tmpBack);
		return feadBackDataLists;
	}
	
	
	private static final String[] parsePatterns = {
			"dd/MM/yyyy HH:mm:ss","yyyy/MM/dd HH:mm:ss",
			"dd-MM-yyyy HH:mm:ss","yyyy-MM-dd HH:mm:ss"
	};

	public Date timeConversion(String dateStr) throws Exception {
		try {
			Date date = null;
			if(StringUtils.isNotBlank(dateStr)) {
				if(dateStr.indexOf("T")>0) {
					dateStr=dateStr.replace("Z", " UTC");//注意是空格+UTC
					SimpleDateFormat form=new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss Z");
					date = form.parse(dateStr);
				}else {
					return DateUtils.parseDate(dateStr, parsePatterns);
				}
			}
			return date;
		} catch (ParseException e) {
			e.printStackTrace();
			throw new Exception("convert date exception: "+dateStr);
		}
	}
}
